package artibella.text 
{
	import artibella.loaders.LoaderURL;
	import flash.errors.IllegalOperationError;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.net.URLLoaderDataFormat;
	import flash.net.URLRequestMethod;
	import flash.text.StyleSheet;
	import flash.text.TextFormat;
	/**
	 * ...
	 * @author pbordachar
	 */
	public class StylesManager extends EventDispatcher
	{
		private static var _instance:StylesManager;
		
		private static var _tabItems:Vector.<LoaderURL>;
		private static var _styleSheet:StyleSheet; 
		
		private var _itemsToLoad:int;
		
		public function StylesManager( c:PrivateClass = null )  
		{
			if( !c ) {
				throw new IllegalOperationError( 'Error : singleton pattern' );
			} else {
				_tabItems = new Vector.<LoaderURL>;
			}
			
			
		}
		
		public static function get instance():StylesManager
		{
			return _instance || ( _instance = new StylesManager( new PrivateClass() ) );
		}
		
		// - - -
		
		public function addItem( url:String ):void
		{
			var item:LoaderURL = new LoaderURL( url );

			_tabItems.push( item );
		}
		
		public function load():void
		{
			var item:LoaderURL;
			
			for ( var i:int = 0; i < _tabItems.length; i ++ ) {
				
				item = _tabItems[ i ] as LoaderURL
				item.addEventListener( Event.COMPLETE, _onItemLoaded );
				item.load();
				
				_itemsToLoad ++;
			}
		}
		
		private function _onItemLoaded( e:Event ):void
		{
			_itemsToLoad --;
			
			if ( _itemsToLoad == 0 ) _onStylesLoaded( );
			
		}
		
		private function _onStylesLoaded( ):void
		{
			_styleSheet = new StyleSheet();
			
			var str:String = "";
			
			trace( " " ); 
			trace( "--- S T Y L E S" ); 
			
			for( var i:int = 0; i < _tabItems.length; i ++ )
			{
				str += _tabItems[ i ].resultat.toString();
				
			}
			
			_styleSheet.parseCSS( str );
				
			for ( var j:int = 0; j < _styleSheet.styleNames.length; j ++)
			{
				trace( _styleSheet.styleNames[ j ] );
			}
			
			trace( " " ); 
			
			dispatchEvent( new Event( Event.COMPLETE ) );
		}
		
		public function getStyle( s:String ):Object
		{
			var style:Object = _styleSheet.getStyle( s  );
			
			return style;
		}
		
		public function getStyleFormat( s:String ):TextFormat
		{
			var style:Object = _styleSheet.getStyle( s  );
			
			var tf:TextFormat = new TextFormat();
			
			if (style.fontFamily == undefined ) {
				trace( "[CSS]", s, "is missing" ); 
				return tf;
			}
			
			tf = _styleSheet.transform( style );
			
			return tf;
			
			
		}
		
		
	}

}

/// - - -

class PrivateClass { }